<template>
    <div id="model-dialog">
        <el-dialog
            :title="basicInfo.titleCon"
            v-model="isDialog" 
            draggable 
            :close-on-click-modal="false" 
            :width="basicInfo.modeWidth" 
            :before-close="handleClose"
            :destroy-on-close="true"
            @close="clean"
        >
            <!-- 基础数据 -->
            <template v-if="modelType.form">
                <el-divider content-position="left">基础信息</el-divider>  
                <el-form :model="ruleForm" ref="ruleFormRef" size="default" :labelWidth="basicInfo.labelWidth" :rules="basicInfo.rules">
                    <el-row>
                        <el-col v-for="(item,index) in Object.keys(ruleForm)" :key="index" :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item :label="VNodeData[index].label" :prop="VNodeData[index].prop">
                                <!-- select -->
                                <el-select 
                                    v-if="VNodeData[index].type === 'select'"
                                    :filterable="VNodeData[index].isFilterable"
                                    :multiple="VNodeData[index].isMultiple"
                                    v-model="ruleForm[item]"
                                    :placeholder="VNodeData[index].placeholder" 
                                    value-key='id'
                                >
                                    <el-option
                                        v-for="em in VNodeData[index].options.data.rows"
                                        :key="em.id"
                                        :label="em.name"
                                        :value="em"
                                    />
                                </el-select>
                                <!-- input -->
                                <el-input 
                                    v-if="VNodeData[index].type === 'input'" 
                                    v-model="ruleForm[item]" 
                                    :type="VNodeData[index].VType" 
                                    :placeholder="VNodeData[index].placeholder" 
                                    clearable 
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </template>

            <template v-if="modelType.upload">
                <!-- 文件上传 -->
                <el-divider content-position="left">文件上传</el-divider>  
                <FileView 
                    ref="fileRef"
                    isAccept=".jpg,.jpeg,.png,.mp4"
                    :fileInfo="fileInfo"
                    :componentKey="componentKey"
                />
            </template>

            <template v-if="modelType.table">
                <!-- 表格数据 -->
                <el-divider content-position="left">表格数据</el-divider>  
                <GetData
                    ref="tabRef"
                    :tabData="tabData"
                ></GetData>
            </template>

            <!-- 其它内容放在插槽中 -->
            <slot name="otherCon"></slot>

            <template #footer>
                <el-button @click="cancelUseClick">{{ basicInfo.cancelInfo }}</el-button>
                <el-button type="primary" :disabled="repeatDis" :loading="repeatDis" @click="submitForm(ruleFormRef)">{{ basicInfo.controlInfo }}</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, reactive , computed , toRefs, watch } from 'vue';
import { 
    FormInstance, 
    ElButton, 
    ElCol, 
    ElDialog, 
    ElForm, 
    ElFormItem, 
    ElInput, 
    ElOption, 
    ElRow, 
    ElSelect, 
    ElMessage, 
} from 'element-plus';
import FileView from './file-view.vue';
import GetData from './getData.vue';
/*** 定义接口基础数据类型 */
interface formType {
    repeatDis: Boolean,
    ruleForm: ruleFormType | any,
    basicInfo: modelInfo | any,
    VNodeData: any,
    modelType: any,
}
/*** 表单基础数据 */
type formInfo = {}
/*** 模型基础数据 */
type modelInfo = {}
/*** form 表单数据类型 */
type ruleFormType = {}

export default defineComponent( {
    name: 'model-dialog',
    components: {
        FileView,
        GetData,
    },
    props: {
        isDialog:{
            type: Boolean,
            default: false,
        },
        modelInfo: {
            type: String,
            default: ''
        },
    },
    setup(props,ctx){
        // 文件上传部分
        const fileInfo = ref('');
        const tabData = ref(''); // 表格数据
        const ruleFormRef = ref(); // 表单ref
        const fileRef = ref(); // 文件上传ref
        const tabRef = ref(); // 表格ref



        /*** state 引用接口定义基础数据初始值 */
        const state = reactive < formType > ({
            repeatDis: false,
            ruleForm: {} as ruleFormType,
            basicInfo: {} as modelInfo ,
            VNodeData: [],
            modelType: {},
        })

        /*** handleClose 关闭按钮点击事件 */
        const handleClose = () => {
            cancelUseClick();
        }

        /*** cancelUseClick 取消事件 */
        const cancelUseClick = () => {
            ctx.emit('cancelModelClick')
        }

        /*** submitForm 提交事件 */
        const submitForm = async(formEl: FormInstance | undefined) => {
            state.repeatDis = true
            if(!formEl) return;
            let param: any = {};
            try{
                if(state.modelType.form){
                    await new Promise<void>((resolve, reject) => {
                        formEl.validate( async (valid) => {
                            if(valid){
                                param.setFormData = state.ruleForm;
                                resolve();
                            }else{
                                reject(new Error('异常退出'))
                            }
                        });
                    });
                };

                if(state.modelType.upload){
                    await new Promise<void>((resolve, reject) => {
                        if(fileRef.value){
                            let len = fileRef.value.fileList.length;
                            if(len === 0){
                                ElMessage({
                                    type: 'error',
                                    message: '请按要求上传文件',
                                    duration: 1500,
                                    onClose: () => {
                                        reject(new Error('异常退出'))
                                    }
                                });
                            }else{
                                param.setUploadData = fileRef.value.fileList;
                                resolve();
                            }
                        }
                    });
                };

                if(state.modelType.table){
                    console.log('封装的数据模型中关于table的数据操作后期在添加完善')
                };
                param.modelType = state.modelType;
                ctx.emit('controlModelClick',param);
                state.repeatDis = false;
            }catch(error){
                console.log(error)
                state.repeatDis = false;
            }          
        }

        /*** clean 清空数据 */
        const clean = () => {
            ruleFormRef.value.resetFields()
        }
        /*** isDialog 响应弹窗的关闭  */
        const isDialog = computed(() => {
            return props.isDialog
        })

        /** 文件上传取消事件 */
        const cancelFileClick = () => {}
        /** 文件上传提交事件 */
        const controlFileClick = () => {}

        /*** 监听isUseDialog的变化 */
        watch(() => props.isDialog,(newVal) => {
            if(newVal){
                console.log(JSON.parse(props.modelInfo),'modelInfo')
                let item = JSON.parse(props.modelInfo);
                state.ruleForm = item.ruleForm;
                state.basicInfo = item.basicInfo;
                state.VNodeData = item.VNodeData;
                state.modelType = item.modelType;
                state.repeatDis = false;
                // 当模型中存在文件上传的模块时需要传 fileInfo
                if(item.modelType.upload) {
                    let param: any = {};
                    param.sourceId = item.rowData.l_FileId;
                    fileInfo.value = JSON.stringify(param);
                }
            }
        })

        return {
            handleClose,
            submitForm,
            cancelUseClick,
            clean,
            ruleFormRef,
            ...toRefs(state),
            isDialog,
            cancelFileClick,
            controlFileClick,
            fileInfo,
            tabData,
            tabRef,
            fileRef,
            componentKey: 1,
        }
    },
} )
</script>
<style scoped lang="scss">
:deep(.el-cascader){
    width: 100%;
}
:deep(.el-select){
    width: 100%!important;
}
:deep(.el-input){
    width: 100%;
}
</style>